#!/usr/bin/python3
# coding=utf-8

import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler
from loguru import logger

LOG_PATH = os.path.join(
    os.path.split(os.path.dirname(os.path.abspath(__file__)))[0], "logs"
)


class LoggerHelper(object):
    def __init__(self, log_base_name="Track"):
        self.logger = logging.getLogger(log_base_name)
        logging.root.setLevel(logging.NOTSET)
        self.log_file = "execution_track.log"
        self.backup_count = 2
        self.console_output_level = "WARNING"
        self.file_output_level = "DEBUG"
        self.formatter = logging.Formatter(
            "%(asctime)s-%(name)s-%(levelname)s-%(message)s"
        )

    def get_log(self):
        # 在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回
        if not self.logger.handlers:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(self.console_output_level)
            self.logger.addHandler(console_handler)
            # 每天重新创建一个日志文件，最多保留backup_count份
            if os.path.exists(LOG_PATH):
                pass
            else:
                os.mkdir(LOG_PATH)
            file_handler = TimedRotatingFileHandler(
                filename=os.path.join(LOG_PATH, self.log_file),
                when="MIDNIGHT",
                interval=1,
                backupCount=self.backup_count,
                delay=True,
                encoding="utf-8",
            )
            file_handler.setLevel(self.file_output_level)
            file_handler.setFormatter(self.formatter)
            self.logger.addHandler(file_handler)

        return self.logger


# Logger = LoggerHelper().get_log()

# 启用三方服务来打印日志
LOG_FILE = "Bill_Engine_Execution.log"
new_file = os.path.join(LOG_PATH, LOG_FILE)
logger.configure(handlers=[{"sink": LOG_FILE, "level": "WARNING"}])
logger.add(new_file, enqueue=True)
logger.add(sys.stdout, level="WARNING")
logObj = logger


if __name__ == "__main__":
    logger.debug("asdadsfg ")
    logger.warning("asdadsfg ")
    # NewLogger.info('yasasd')
